﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

namespace Homework4
{
    static class MethodExtensions
    {
        public static void AppendStrings(this StringBuilder builder, IEnumerable<string> items, string format, string separator)
        {
            foreach (var item in items)
            {
                builder.AppendFormat(format + separator, item);
            }

            if (!string.IsNullOrEmpty(separator))
            {
                builder.Remove(builder.Length - separator.Length, separator.Length); // Remove trailing separator
            }
        }

        public static SecureString ToSecureString(this string insecureString)
        {
            var secureStr = new SecureString();
            if (insecureString.Length > 0)
            {
                foreach (var c in insecureString.ToCharArray())
                {
                    secureStr.AppendChar(c);
                }
            }
            return secureStr;
        }

        public static string ToInsecureString(this SecureString secureString)
        {
            var unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }

        public static string GetBase(this Uri uri)
        {
            return uri.Scheme + "://" + uri.Authority;
        }

        public static string GetBaseWithPath(this Uri uri)
        {
            return uri.Scheme + "://" + uri.Authority + "/" + uri.LocalPath;
        }

        public static string GetRealHost(this Uri uri)
        {
            if (uri.Host.Count(f => f == '.') > 1)
            {
                var split = uri.Host.Split('.');
                return split[split.Length - 2] + "." + split[split.Length - 1]; // Last 2 components
            }
            else
            {
                return uri.Host; // Host component is only like 'google.com' or even 'google'
            }
        }
    }
}
